
import serial
import serial.tools.list_ports as ser_port_list

class Serial():
    def __init__(self, port=None, baudrate=9600, timeout=10):
        self.data = 0
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.serial_open()

    # 读串口
    def serial_read(self):
        raw_data = self.__ser.readline().decode('gbk').strip("\r\n")
        
        if len(raw_data) >= 1 and not raw_data is None:   
            self.data = int(raw_data)
            
    # 打开串口
    def serial_open(self):
        self.__ser = serial.Serial(self.port, self.baudrate, timeout = self.timeout)
    
    def __getattr__(self, name):
        try:
            return getattr(self.__ser, name)
        except AttributeError:
            raise AttributeError(
                "'{}' object has no attribute '{}'".format(self.__class__.__name__, name)
            )         

    # 获取本机串口
    @staticmethod
    def serial_check():
        return list(ser_port_list.comports())
